<template>
  <div>
    <!-- 留言列表 -->
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
    >
      <div v-for="message in messages" :key="message.id">
        {{ message.content }}
      </div>
    </van-list>

    <!-- 分页 -->
    <van-pagination
      v-model="currentPage"
      :page-count="totalPages"
      mode="simple"
      @change="handlePageChange"
    />

    <!-- 留言表单 -->
    <van-form @submit="submitMessage" style="margin-top: 20px">
      <van-field
        v-model="messageForm.content"
        name="content"
        label="留言内容"
        type="textarea"
        placeholder="请输入留言内容"
        :rules="[{ required: true, message: '留言内容不能为空' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { showToast } from 'vant'
import request from '@/utils/request'

// 表单数据
const messageForm = ref({
  content: '',
})

// 留言列表数据
const messages = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const finished = ref(false)

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 获取留言列表
const fetchMessages = async (page = 1) => {
  try {
    const response = await request.get('/api/message-board/page', {
      params: {
        page,
        size: pageSize.value,
      },
    })
    messages.value = response.data.records
    total.value = response.data.total
    finished.value = currentPage.value >= totalPages.value
  } catch (error) {
    console.error('获取留言列表时出错:', error)
    showToast('获取留言列表时出错，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 提交留言
const submitMessage = async () => {
  try {
    await request.post('/api/message-board/add/auth', messageForm.value)
    messageForm.value = { content: '' } // 清空表单
    fetchMessages() // 重新加载留言列表
    showToast('留言提交成功')
  } catch (error) {
    console.error('提交留言时出错:', error)
    showToast('提交留言时出错，请稍后重试')
  }
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page
  fetchMessages(page)
}

// 列表加载更多
const onLoad = () => {
  if (!finished.value) {
    currentPage.value += 1
    fetchMessages(currentPage.value)
  }
}

// 组件挂载时加载留言列表
onMounted(() => {
  fetchMessages()
})
</script>
<style scoped>
h1 {
  text-align: center;
  margin-bottom: 20px;
}

.van-list {
  margin-bottom: 20px;
}

.van-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>